// src/utils/api.ts
import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
// import { useUserStore } from "@stores/user";
import { useUserStore } from "@/stores";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import router from "@/router";

// 定义接口返回数据的通用格式
export interface ApiResponse<T = any> {
  code: number;
  data: T;
  msg: string;
}

// 创建 axios 实例
const instance: AxiosInstance = axios.create({
  baseURL:
    import.meta.env.VITE_API_BASE_URL + import.meta.env.VITE_GLOB_API_URL, // 使用 Vite 的环境变量
  timeout: 10000000, // 请求超时时间
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    if (response.data.code === 401 || response.data.code === 509) {
      const userStore = useUserStore();
      localStorage.clear();
      ElMessage.error(response.data.msg || "登录已过期，请重新登录");
      userStore.logout();
      router.push("/auth/login");
      return Promise.reject(new Error("Unauthorized"));
    } else if (response.data.code !== 200) {
      ElMessage.error(response.data.msg || "请求失败");
      return Promise.reject(response.data.msg || "请求失败");
    }
    return response.data;
  },
  (error) => {
    console.log("err" + error);
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage({ message: message, type: "error", duration: 5 * 1000 });
    return Promise.reject(error);
  }
);

// 封装通用的请求方法
export const request = <T = any>(config: AxiosRequestConfig): Promise<T> => {
  return instance.request<T, T>(config);
};

// 导出常用的请求方法
export const get = <T = any>(
  url: string,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request({ method: "GET", url, ...config });
};

export const post = <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request({ method: "POST", url, data, ...config });
};

export const put = <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request({ method: "PUT", url, data, ...config });
};

export const del = <T = any>(
  url: string,
  config?: AxiosRequestConfig
): Promise<T> => {
  return request({ method: "DELETE", url, ...config });
};

export default request;
